<script setup lang="tsx">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { QuestionOptionVO } from '#/api/config/questionnaires/question/model';

import { onMounted, ref, watch } from 'vue';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import { LinkOutlined } from '@ant-design/icons-vue';
import { Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  questionInfo,
  questionOptionChangeSort,
  questionOptionList,
  // questionOptionInfo,
  questionOptionRemove,
  questionOptionUpdateStatus,
} from '#/api/config/questionnaires/question';
// import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';
import { renderDict } from '#/utils/render';

import { columns } from './data';
import questionOptionModal from './option-modal.vue';

const props = defineProps<{
  questionId: number | string;
  questionType: number | string;
}>();

const emit = defineEmits<{ reload: [] }>();

const { hasAccessByCodes } = useAccess();
const tableTitle = ref<string>('');

const [QuestionOptionModal, questionOptionModalApi] = useVbenModal({
  connectedComponent: questionOptionModal,
});

// const [TagDetailsModal, tagDetailsModalApi] = useVbenModal({
//   connectedComponent: DetailsModal,
// });

const gridOptions: VxeGridProps = {
  columns,
  height: 'auto',
  keepSource: false,
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        if (!props.questionId) {
          return { rows: [] };
        }

        const resp = await questionInfo(props.questionId);
        const optionList = await questionOptionList({
          questionId: props.questionId,
        });
        tableTitle.value = `${resp.name}`;
        return { rows: optionList || [] };
      },
    },
  },
  // toolbarConfig: {
  //   enabled: true,
  //   custom: true,
  //   zoom: false,
  // },
  rowConfig: {
    keyField: 'id',
    drag: true,
    isCurrent: true,
  },
  id: 'questionnaires-question-option-list',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents: {
    rowDragend: async ({ newRow, oldRow, dragPos }) => {
      console.log(
        `拖拽完成，被拖拽行：${oldRow.name} 目标行：${newRow.name} 目标位置：${dragPos}`,
      );
      const tableList = tableApi.grid.getTableData()?.tableData ?? [];
      const sortedList = tableList.map((item, index) => {
        return { id: item.id, name: item.name, sort: index + 1 };
      });
      console.log('拖拽后表格数据：', sortedList);
      await questionOptionChangeSort(sortedList as QuestionOptionVO[]);
      emit('reload');
    },
  },
});

watch(
  () => props.questionId,
  async () => {
    await tableApi.reload();
  },
);

onMounted(async () => {
  //
});

async function handleAdd() {
  questionOptionModalApi.setData({
    questionId: props.questionId,
    questionType: props.questionType,
  });
  questionOptionModalApi.open();
}

// async function handlePreview(row: QuestionOptionVO) {
//   tagDetailsModalApi.setData(row);
//   tagDetailsModalApi.open();
// }

async function handleEdit(row: QuestionOptionVO) {
  questionOptionModalApi.setData({
    questionId: props.questionId,
    questionType: props.questionType,
    id: row.id,
  });
  questionOptionModalApi.open();
}

async function handleDelete(row: QuestionOptionVO) {
  await questionOptionRemove([row.id]);
  await tableApi.query();
  emit('reload');
}

async function questionOptionStatusUpdate(row: QuestionOptionVO) {
  const data = {
    id: row.id,
    status: row.status,
  };
  await questionOptionUpdateStatus(data);
  emit('reload');
}

async function handleOptionUpdated() {
  await tableApi.query();
  emit('reload');
}
</script>

<template>
  <BasicTable>
    <template #table-title>
      <div class="flex items-center gap-2">
        {{ tableTitle }}
        <component
          :is="
            renderDict(questionType, DictEnum.QUESTIONNAIRE_QUESTION_TYPE, true)
          "
        />
      </div>
    </template>
    <template #toolbar-tools>
      <Space>
        <a-button
          v-access:code="['question:option:add']"
          type="primary"
          @click="handleAdd"
        >
          新增题目选项
        </a-button>
      </Space>
    </template>
    <template #name="{ row }">
      <div>{{ row.name }}</div>
      <div
        v-if="row.secondaryQuestionName"
        class="mt-[10px] pl-[15px] text-[#909399]"
      >
        <LinkOutlined />
        关联题目：{{ row.secondaryQuestionName }}
      </div>
    </template>
    <template #status="{ row }">
      <TableSwitch
        v-model:value="row.status"
        :api="() => questionOptionStatusUpdate(row)"
        :disabled="!hasAccessByCodes(['question:option:edit'])"
        @reload="tableApi.query()"
      />
    </template>
    <template #action="{ row }">
      <Space>
        <!--<ghost-button-->
        <!--  v-access:code="['question:option:query']"-->
        <!--  @click="handlePreview(row)"-->
        <!--&gt;-->
        <!--  详情-->
        <!--</ghost-button>-->
        <ghost-button
          v-access:code="['question:option:edit']"
          @click="handleEdit(row)"
        >
          编辑
        </ghost-button>
        <Popconfirm
          placement="left"
          ok-type="danger"
          title="确认删除这条题目选项？"
          @confirm="handleDelete(row)"
        >
          <ghost-button
            danger
            v-access:code="['question:option:remove']"
            @click.stop=""
          >
            删除
          </ghost-button>
        </Popconfirm>
      </Space>
    </template>
  </BasicTable>
  <QuestionOptionModal @reload="handleOptionUpdated" />
  <!--<QuestionOptionDetailsModal :columns="questionOptionDetailsSchema()" :api="questionOptionInfo" />-->
</template>
